﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace MvcArchStarter.Infrastructure.Persistence
{
    public static class ExpressionExtensions
    {
        public static string GetExpressionPath(this Expression exp)
        {
            if (exp == null)
                throw new ArgumentNullException("exp");

            switch (exp.NodeType)
            {
                case ExpressionType.MemberAccess:
                    var name = GetExpressionPath(((MemberExpression)exp).Expression) ?? "";

                    if (name.Length > 0)
                        name += ".";

                    return name + ((MemberExpression)exp).Member.Name;
                case ExpressionType.Call:
                    return GetExpressionPath(((MethodCallExpression)exp).Object);
                case ExpressionType.Convert:
                case ExpressionType.Quote:
                    return GetExpressionPath(((UnaryExpression)exp).Operand);

                case ExpressionType.Lambda:
                    return GetExpressionPath(((LambdaExpression)exp).Body);

                default:
                    return null;
            }
        }
    }

}
